package org.lagou.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.lagou.pojo.Configuration;
import org.lagou.pojo.MapperStatement;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }
    
    public void parseMapper(InputStream inputStream) throws DocumentException {
        
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = rootElement.selectNodes("//select");
        putMapperStatement(namespace, list, "select");

        List<Element> listDelete = rootElement.selectNodes("//delete");
        List<Element> listUpdate = rootElement.selectNodes("//update");
        List<Element> listInsert = rootElement.selectNodes("//insert");
        listDelete.addAll(listUpdate);
        listDelete.addAll(listInsert);
        putMapperStatement(namespace, listDelete, "update");
    }

    private void putMapperStatement(String namespace, List<Element> list, String sqlType) {
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getText();
            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            mapperStatement.setResultType(resultType);
            mapperStatement.setParamType(parameterType);
            mapperStatement.setSql(sqlText);
            mapperStatement.setSqlType(sqlType);
            String key = namespace + "." + id;
            configuration.getMapperStatementMap().put(key,mapperStatement);
        }
    }

}
